<?php

namespace app\admin\controller;

use Alipay\EasySDK\Kernel\Factory as alipayFactory;
use app\admin\model\User;
use app\api\model\MerchantCarTime;
use app\common\controller\Backend;
use app\common\model\MerchantCar;
use app\common\model\Order as OrderModel;
use EasyWeChat\Factory;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Db;
use think\Model;

/**
 * 换车订单管理
 *
 * @icon fa fa-circle-o
 */
class OrderChange extends Backend
{
    
    /**
     * OrderChange模型对象
     * @var \app\admin\model\OrderChange
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $order_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\OrderChange;
        $statusList = \app\admin\model\OrderChange::fetchStatus();
        $payTypeList = \app\admin\model\OrderChange::fetchPayType();
        $typeList = \app\admin\model\OrderChange::fetchType();
        $this->view->assign(['statusList' => $statusList, 'payTypeList' => $payTypeList, 'typeList' => $typeList]);
        $this->assignconfig(['statusList' => $statusList, 'payTypeList' => $payTypeList, 'typeList' => $typeList]);
        $order_id = $this->request->param('order_id');
        $this->order_id = $order_id;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看.
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $builder = $this->model
                ->withJoin(['user', 'merchant_car', 'order'])
                ->where($where)
                ->where('order_change.is_delete', 1);
            if($this->order_id){
                $builder->where('order_change.order_id', $this->order_id);
            }
            $total = $builder
                ->order($sort, $order)
                ->count();
            $list  = $builder
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = ['total' => $total, 'rows' => $list];

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $order = \app\admin\model\Order::where(['is_delete' => 1, 'id' => $this->order_id])->find();
        if(!$order){
            $this->error('订单不存在');
        }
        if($order['status'] != 1){
            $text = \app\admin\model\Order::fetchStatus($order['status']);
            $this->error('订单'.$text);
        }
        if($order['change_status'] == 2){
            $this->error('订单换车中');
        }
        if($order['merchant_car_id']){
            $merchant_car = \app\admin\model\MerchantCar::with('cars')->where(['is_delete' => 1, 'id' => $order['merchant_car_id']])->find();
            if(!$merchant_car){
                $this->error('商家车辆不存在');
            }
            if($merchant_car['status'] == 2){
                $this->error('商家车辆已下架');
            }
        }
        //最后一个有车辆的换车订单
        $last_merchant_order = \app\admin\model\OrderChange::where(['is_delete' => 1, 'user_id' => $order['user_id'], 'order_id' => $order['id']])->where('pay_status', 'in', '2')->where('merchant_car_id', '>', 0)->order('createtime', 'desc')->find();
        if($last_merchant_order){
            $merchant_car = MerchantCar::with('cars')->where('id', $last_merchant_order['merchant_car_id'])->find();
        }
        //最后一个换车订单
        $last_change_order = \app\admin\model\OrderChange::where(['is_delete' => 1, 'user_id' => $order['user_id'], 'order_id' => $order['id']])->where('pay_status', 'in', '2')->order('createtime', 'desc')->find();
        if($last_change_order){
            if($last_change_order['merchant_car_id'] > 0){
                $last_car_number = MerchantCar::where('id', $last_change_order['merchant_car_id'])->value('car_number');
            }else{
                $last_car_number = $last_change_order['other_number'];
            }
            $order['car_number'] = $last_car_number;
            $merchant_car['car_number'] = $last_car_number;
        }

        //订单换车订单
        $order_change = \app\admin\model\OrderChange::where(['is_delete' => 1, 'order_id' => $order['id'], 'pay_status' => 1])->count();
        if($order_change){
            $this->error('该订单已有待支付的换车订单');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'add' : $name)->check($params);
                    }
                    $user = User::where('id', $order['user_id'])->find();
                    if($params['type'] == 1){
                        if(!$params['other_number'] && !$params['merchant_car_id']){
                            $this->error('车辆不能为空');
                        }
                    }else{
                        if(!$params['merchant_car_id']){
                            $this->error('车辆不能为空');
                        }
                    }
                    $rental_money = 0;
                    $diff_money = 0;
                    $all_money = 0;
                    $car_deposit = 0;
                    $pick_fee = 0;
                    $return_fee = 0;
                    $handle_fee = 0;

                    if($params['merchant_car_id']){
                        $merchant_car = \app\admin\model\MerchantCar::with('cars')->where(['is_delete' => 1, 'id' => $params['merchant_car_id']])->find();
                        if(!$merchant_car){
                            $this->error('商家车辆不存在');
                        }
                        if($merchant_car['status'] == 2){
                            $this->error('商家车辆已下架');
                        }
                        $handle_fee = $merchant_car['handle_fee'];

                        //临时下架时间
                        $last_time = strtotime("-1 month");
                        $merchant_car_time = MerchantCarTime::where(['is_delete' => 1, 'merchant_car_id' => $params['merchant_car_id']])->where('end_time', '>', $last_time)->select();
                        foreach ($merchant_car_time as $ke=>$vl){
                            $is_time_cross = is_time_cross($vl['start_time'], $vl['end_time'], $order['start_time'], $order['end_time']);
                            if($is_time_cross){
                                $this->error('租赁时间段内商家车辆会临时下架');
                            }
                        }

                        $merchant = \app\admin\model\Merchant::where('id', $order['merchant_id'])->find();
                        $stay_area = false;
                        //判断区域 确定取车还车价格
                        $merchant_area = \app\admin\model\MerchantArea::field('id,price,area,stay_time')->where(['is_delete' => 1, 'status' => 1, 'merchant_id' => $order['merchant_id']])->select()->toArray();
                        $point = explode(',', $order['pick_point']);
                        foreach ($merchant_area as $kee => $vll){
                            //判断是否在区域内
                            $area = getNewArea($vll['area']);
                            $is_area = is_ptin_poly($point[0], $point[1], $area);
                            if($is_area){
//                                if($order['start_time'] - time() < $vll['stay_time']){
//                                    $this->error('改区域商家提前等待时间最少为'.$vll['stay_time'].'分钟');
//                                }
                                $pick_fee = $vll['price'];
                                $return_fee = $vll['price'];
                                $stay_area = true;
                            }
                        }
//                        if(!$stay_area){
//                            if($order['start_time'] - time() < $merchant['stay_time']*60){
//                                return ['status' => 0, 'message' => '商家提前等待时间最少为'.$merchant['stay_time'].'分钟', 'result' => ''];
//                            }
//                        }

                        //商家车辆远期价格
                        $date_list = createDateRange(date('Y-m-d', $order['start_time']), date('Y-m-d', $order['end_time']));
                        $merchant_car_price_list = \app\admin\model\MerchantCarPrice::field('start_time,end_time,price,days')->where(['is_delete' => 1, 'merchant_car_id' => $params['merchant_car_id']])->where('end_time', '>', time())->select()->toArray();
                        $new_date_list = [];
                        if($merchant_car_price_list){
                            foreach ($date_list as $kk=>$vv){
                                $new_date['date'] = $vv;
                                $new_date['price'] = $merchant_car['car_price'];
                                foreach ($merchant_car_price_list as $kkk=>$vvv){
                                    if(strtotime($vv) >= $vvv['start_time'] && strtotime($vv) <= $vvv['end_time']){
                                        if($order['days'] < $vvv['days']){
                                            return ['status' => 0, 'message' => '起租天数必须大于' . $vvv['days'] , 'result' => ''];
                                        }
                                        $new_date['price'] = $vvv['price'];
                                    }
                                }
                                $new_date_list[] = $new_date;
                            }
                            $price_list = array_column($new_date_list, 'price');
                            $prices = implode(',', $price_list);
                            //租车费用
                            $rental_money = array_sum($price_list);
                        }else{
                            $prices = $order['price'];
                            $rental_money = bcmul($order['price'], $order['days'], 2);
                        }

                        $car_deposit = $merchant_car['car_deposit']??0;
                    }

                    $coupon_money = 0;
                    if($params['type'] == 2 && $order['coupon_id']){
                        $coupon_money = $order['coupon_money'];
                        if($coupon_money < $rental_money){
                            $this->error('租赁金额未达到之前的优惠金额');
                        }
                    }
                    $all_money = bcadd($rental_money-$coupon_money, ($pick_fee+$return_fee+$order['night_pick_fee']+$order['night_return_fee']+$handle_fee+$order['insurance_money']), 2);
                    //查询最后一个有偿换车订单
                    $last_pay_order = \app\admin\model\OrderChange::where(['is_delete' => 1, 'user_id' => $order['user_id'], 'order_id' => $order['id'], 'type' => 2])->where('pay_status', 'in', '2')->order('createtime', 'desc')->find();
                    if(!$last_pay_order){
                        $diff_money = $params['type'] == 1 ? 0 : bcsub($all_money, $order['all_money'], 2);
                    }else{
                        $diff_money = $params['type'] == 1 ? 0 : bcsub($all_money, $last_pay_order['all_money'], 2);
                        $order['price'] = $last_pay_order['price'];
                    }

                    if($params['type'] == 1){
                        $pay_status = 2;
                        $change_status = 3;
                    }else{
                        if($diff_money > 0){
                            $pay_status = 1;
                            $change_status = 2;
                        }else{
                            $pay_status = 2;
                            $change_status = 3;
                        }
                    }
                    $params['user_id']  = $order['user_id'];
                    $params['order_id']  = $order['id'];
                    $params['out_trade_no']  = \app\admin\model\OrderChange::getOutRefundNo();
                    $params['merchant_id']  = $order['merchant_id'];
                    $params['merchant_car_id']  = $params['merchant_car_id'] ? $params['merchant_car_id'] : 0;
                    $params['price']  = $params['type'] == 2 ? $merchant_car['price'] : 0;
                    $params['rental_money']  = $params['type'] == 2 ? $rental_money : 0;
                    $params['deposit']  = $params['type'] == 2 ? $car_deposit : 0;
                    $params['deposit_status']  = ($params['type'] == 2 && $car_deposit) > 0 ? 1 : 0;
                    $params['all_money']  = $params['type'] == 2 ? $all_money : 0;
                    $params['diff_money']  = $params['type'] == 2 ? $diff_money : 0;
                    $params['pay_type']  = $order['pay_type'];
                    $params['createtime']  = time();
                    $params['old_merchant_car_id']  = $order['merchant_car_id'];
                    $params['old_price']  = $order['price'];
                    $params['pay_status'] = $pay_status;
                    $params['change_status'] = $change_status;
                    $params['last_all_money'] = $diff_money > 0 ? $diff_money : 0;
                    $params['pick_fee'] = $params['type'] == 2 ? $pick_fee : 0;
                    $params['return_fee'] = $params['type'] == 2 ? $return_fee : 0;
                    $params['prices'] = $params['type'] == 2 ? $prices : '';
                    $params['handle'] = $params['type'] == 2 ? $handle_fee : 0;
                    $params['night_pick_fee'] = $params['type'] == 2 ? $order['night_pick_fee'] : 0;
                    $params['night_return_fee'] = $params['type'] == 2 ? $order['night_return_fee'] : 0;
                    $params['handle'] = $params['type'] == 2 ? $handle_fee : 0;
                    $result = $this->model->save($params);
                    $change_order_id = $this->model->id;
                    //更改主订单数据
                    if($result){
                        $update = ['change_status' => $change_status];
                        \app\admin\model\Order::where('id', $order['id'])->update($update);
                        \app\admin\model\Order::where('id', $order['id'])->inc('change_num', 1)->update();
                        if($params['type'] == 2 && $diff_money < 0){
                            //需退款 统计换车退款金额
                            \app\admin\model\Order::where('id', $order['id'])->inc('all_change_refund_money', abs($diff_money))->update();
                        }
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            $this->view->assign('order', $order);
            $this->view->assign('merchant_car', $merchant_car);
            return $this->view->fetch();
        }
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model
            ->field('out_trade_no,user_id,merchant_id,merchant_car_id,price,rental_money,pick_fee,return_fee,all_money,diff_money,pay_type,type,pay_status,createtime,time_end,total_fee,out_refund_no,refund_id,refund_time,refund_money')
            ->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if($row){
            $user = User::where('id', $row['user_id'])->find();
            $row['user_id'] = $user['username'];
            $merchant = \app\admin\model\Merchant::where('id', $row['merchant_id'])->find();
            $row['shop_name'] = $merchant['shop_name'];
            $row['shop_address'] = $merchant['province'] . $merchant['city'] . $merchant['area'] . $merchant['street'];
            $merchant_car = \app\admin\model\MerchantCar::with('cars')->where('id', $row['merchant_car_id'])->find();
            $row['car_name'] = $merchant_car['car_name'];
            $row['pay_status'] = \app\admin\model\OrderChange::fetchStatus($row['pay_status']);
            $row['pay_type'] = \app\admin\model\OrderChange::fetchPayType($row['pay_type']);
            $row['type'] = \app\admin\model\OrderChange::fetchType($row['type']);
            $row['type'] = $row['type'] == 1 ? '否' : '是';
            $row['createtime'] = date('Y-m-d H:i:s', $row['createtime']);
            $row['time_end'] = $row['time_end'] ? date('Y-m-d H:i:s', $row['time_end']) : '';
            $row['refund_time'] = $row['refund_time'] ? date('Y-m-d H:i:s', $row['refund_time']) : '';
            unset($row['merchant_id'],$row['merchant_car_id']);
        }
//        dump($row);die;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where('id', 'in', $ids)->update(['is_delete' => 2, 'deletetime' => time()]);
        $this->success();
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        $ids = $this->request->param('ids');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['pay_status'] != 2 || $row['pay_status'] != 1){
            $text = \app\admin\model\OrderChange::fetchStatus($row['pay_status']);
            $this->error('订单'.$text);
        }
        if(!$this->request->isPost()){
            return $this->view->fetch();
        }
        Db::startTrans();
        try {
            $params = $this->request->post('row/a');
            $user_model = new User();
            if($row['pay_status'] == 2){
                $update = ['pay_status' => 3, 'cancel_time' => time(), 'cancel_reason' => $params['cancel_reason']];
                $out_refund_no = \app\admin\model\OrderChange::getOutRefundNo();
                $update['out_refund_no'] = $out_refund_no;
                //退款接口
                $user = $user_model->where('id', $row['user_id'])->find();
                if($row['pay_type'] == 1){//微信退款
                    $res = $this->refund($row, $user, $row['last_all_money']);
                    if($res['return_code'] == 'SUCCESS' && $res['result_code']=='SUCCESS'){
                        $update['out_refund_no'] = $out_refund_no;
                        $update['refund_id'] = $res['refund_id'];
                        $update['refund_time'] = time();
                        $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                        $update['last_all_money'] = 0;
                        //更新订单
                        $res = $this->model->where('id', $row['id'])->update($update);
                        \app\admin\model\Order::where('id', $row['order_id'])->dec('change_num', 1)->update();
                        if($res){
                            $platform_log = [
                                'user_id' => $row['user_id'],
                                'amount' => $row['last_all_money'],
                                'type' => 9,
                                'log_note' => '续租订单退款',
                                'order_id' => $row['id'],
                                'order_type' => 1,
                                'createtime' => time(),
                                'total_order_id' => $row['order_id']
                            ];
                            \app\common\model\PlatformLog::insert($platform_log);
                        }
                    }else{
                        Db::rollback();
                        $this->error('取消失败');
                    }
                }else{
                    $res = $this->alipayRefund($row, $user, $row['last_all_money']);
                    if($res['code'] == '10000'){
                        $update['out_refund_no'] = $out_refund_no;
                        $update['refund_id'] = $res['trade_no'];
                        $update['refund_time'] = time();
                        $update['refund_money'] = $res['refund_fee'];
                        $update['last_all_money'] = 0;
                        //更新订单
                        $res = $this->model->where('id', $row['id'])->update($update);
                        \app\admin\model\Order::where('id', $row['order_id'])->dec('change_num', 1)->update();
                        if($res){
                            $platform_log = [
                                'user_id' => $row['user_id'],
                                'amount' => $row['last_all_money'],
                                'type' => 9,
                                'log_note' => '续租订单退款',
                                'order_id' => $row['id'],
                                'order_type' => 1,
                                'createtime' => time(),
                                'total_order_id' => $row['order_id']
                            ];
                            \app\common\model\PlatformLog::insert($platform_log);
                        }
                    }else{
                        Db::rollback();
                        $this->error('取消失败');
                    }
                }
                //更新主订单
                $count = $this->model->where(['is_delete' => 1, 'order_id' => $row['order_id']])->where('pay_status', 'in', '1,2')->count();
                if($count == 0){
                    \app\admin\model\Order::where('id', $row['order_id'])->update(['change_status' => 4]);
                }
            }else{
                $update = ['cancel_time' => time(), 'pay_status' => 3, 'cancel_reason' => $params['cancel_reason'], 'last_all_money' => 0];
                //更新订单
                $res = $this->model->where('id', $row['id'])->update($update);
            }
            //更新总订单
            \app\admin\model\Order::where('id', $row['order_id'])->update(['change_status' => 4]);
            Db::commit();
            $this->success('取消订单成功！');
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 退款
     */
    public function return()
    {
        $ids = $this->request->param('ids');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['pay_status'] != 2){
            $text = \app\admin\model\OrderChange::fetchStatus($row['pay_status']);
            $this->error('订单'.$text);
        }
        if(!$this->request->isPost()){
            return $this->view->fetch();
        }
        Db::startTrans();
        try {
            $params = $this->request->post('row/a');
            if($params['refund_money'] > $row['last_all_money']){
                $this->error('超出订单剩余金额');
            }
            $user_model = new User();
            $update = ['pay_status' => 4];
            $out_refund_no = \app\admin\model\OrderChange::getOutRefundNo();
            $update['out_refund_no'] = $out_refund_no;
            //退款接口
            $user = $user_model->where('id', $row['user_id'])->find();
            if($row['pay_type'] == 1){//微信退款
                $res = $this->refund($row, $user, $params['refund_money']);
                if($res['return_code'] == 'SUCCESS' && $res['result_code']=='SUCCESS'){
                    $update['out_refund_no'] = $out_refund_no;
                    $update['refund_id'] = $res['refund_id'];
                    $update['refund_time'] = time();
                    $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                    $last_all_money = bcsub($row['last_all_money'], $params['refund_money'], 2);
                    $update['last_all_money'] = $last_all_money > 0 ? $last_all_money : 0;
                    //更新订单
                    $res = $this->model->where('id', $row['id'])->update($update);
                    $this->model->where('id', $row['id'])->dec('last_all_money', $params['refund_money'])->update();
                    if($res){
                        $platform_log = [
                            'user_id' => $row['user_id'],
                            'amount' => $params['refund_money'],
                            'type' => 7,
                            'log_note' => '换车订单退款',
                            'order_id' => $row['id'],
                            'order_type' => 1,
                            'createtime' => time(),
                            'total_order_id' => $row['order_id']
                        ];
                        \app\common\model\PlatformLog::insert($platform_log);
                    }
                }else{
                    Db::rollback();
                    $this->error('退款失败');
                }
            }else{
                $res = $this->alipayRefund($row, $user, $params['refund_money']);
                if($res['code'] == '10000'){
                    $update['out_refund_no'] = $out_refund_no;
                    $update['refund_id'] = $res['trade_no'];
                    $update['refund_time'] = time();
                    $update['refund_money'] = $res['refund_fee'];
                    $last_all_money = bcsub($row['last_all_money'], $params['refund_money'], 2);
                    $update['last_all_money'] = $last_all_money > 0 ? $last_all_money : 0;
                    //更新订单
                    $res = $this->model->where('id', $row['id'])->update($update);
                    $this->model->where('id', $row['id'])->dec('last_all_money', $params['refund_money'])->update();
                    if($res){
                        $platform_log = [
                            'user_id' => $row['user_id'],
                            'amount' => $params['refund_money'],
                            'type' => 7,
                            'log_note' => '换车订单退款',
                            'order_id' => $row['id'],
                            'order_type' => 1,
                            'createtime' => time(),
                            'total_order_id' => $row['order_id']
                        ];
                        \app\common\model\PlatformLog::insert($platform_log);
                    }
                }else{
                    Db::rollback();
                    $this->error('退款失败');
                }
            }
            Db::commit();
            $this->success('退款成功！');
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    //微信退款
    public function refund($order, $user, $refund_money){
        $refundFee = $refund_money*100;
        $config = Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $result = $app->refund->byOutTradeNumber($order['out_trade_no'], $order['out_refund_no'], $order['all_money']*100, $refundFee, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '订单退款',
        ]);
        return $result;
    }

    //支付宝退款
    public function alipayRefund($order, $user, $refund_money){
        $refundFee = $refund_money*100;
        alipayFactory::setOptions(getOption());
        $result = alipayFactory::payment()->common()->refund($order['out_trade_no'], $refundFee);
        if(!$result){
            return false;
        }
        if($result->code != 10000){
            return false;
            $result->msg."，".$result->sub_msg.PHP_EOL;
        }
        $return_result = json_decode($result->httpBody, true);
        return $return_result['alipay_trade_refund_response'];
    }

    /**
     * 差价计算.
     */
    public function summoney()
    {
        if($this->request->isPost()){
            $order_id = $this->request->param('order_id');
            $type = $this->request->param('type');
            $merchant_car_id = $this->request->param('merchant_car_id');

            $order = \app\admin\model\Order::where(['is_delete' => 1, 'id' => $order_id])->find();
            $merchant_car = \app\admin\model\MerchantCar::with('cars')->where(['is_delete' => 1, 'id' => $merchant_car_id])->find();
            if(!$merchant_car){
                $this->error('商家车辆不存在');
            }
            if($merchant_car['status'] == 2){
                $this->error('商家车辆已下架');
            }
            $handle_fee = $merchant_car['handle_fee'];
            $pick_fee = 0;
            $return_fee = 0;

            //临时下架时间
            $last_time = strtotime("-1 month");
            $merchant_car_time = \app\admin\model\MerchantCarTime::where(['is_delete' => 1, 'merchant_car_id' => $merchant_car_id])->where('end_time', '>', $last_time)->select();
            foreach ($merchant_car_time as $ke=>$vl){
                $is_time_cross = is_time_cross($vl['start_time'], $vl['end_time'], $order['start_time'], $order['end_time']);
                if($is_time_cross){
                    $this->error('租赁时间段内商家车辆会临时下架');
                }
            }

            $merchant = \app\admin\model\Merchant::where('id', $order['merchant_id'])->find();
            $stay_area = false;
            //判断区域 确定取车还车价格
            $merchant_area = \app\admin\model\MerchantArea::field('id,price,area,stay_time')->where(['is_delete' => 1, 'status' => 1, 'merchant_id' => $order['merchant_id']])->select()->toArray();
            $point = explode(',', $order['pick_point']);
            foreach ($merchant_area as $kee => $vll){
                //判断是否在区域内
                $area = getNewArea($vll['area']);
                $is_area = is_ptin_poly($point[0], $point[1], $area);
                if($is_area){
                    if($order['start_time'] - time() < $vll['stay_time']){
                        $this->error('改区域商家提前等待时间最少为'.$vll['stay_time'].'分钟');
                    }
                    $pick_fee = $vll['price'];
                    $return_fee = $vll['price'];
                    $stay_area = true;
                }
            }

            if(!$stay_area){
                if($order['start_time'] - time() < $merchant['stay_time']*60){
                    return ['status' => 0, 'message' => '商家提前等待时间最少为'.$merchant['stay_time'].'分钟', 'result' => ''];
                }
            }

            //商家车辆远期价格
            $date_list = createDateRange(date('Y-m-d', $order['start_time']), date('Y-m-d', $order['end_time']));
            $merchant_car_price_list = \app\admin\model\MerchantCarPrice::field('start_time,end_time,price,days')->where(['is_delete' => 1, 'merchant_car_id' => $merchant_car_id])->where('end_time', '>', time())->select()->toArray();
            $new_date_list = [];
            foreach ($date_list as $kk=>$vv){
                $new_date['date'] = $vv;
                $new_date['price'] = $merchant_car['car_price'];
                foreach ($merchant_car_price_list as $kkk=>$vvv){
                    if(strtotime($vv) >= $vvv['start_time'] && strtotime($vv) <= $vvv['end_time']){
                        if($order['days'] < $vvv['days']){
                            return ['status' => 0, 'message' => '起租天数必须大于' . $vvv['days'] , 'result' => ''];
                        }
                        $new_date['price'] = $vvv['price'];
                    }
                }
                $new_date_list[] = $new_date;
            }
            $price_list = array_column($new_date_list, 'price');
            //租车费用
            $rental_money = array_sum($price_list);
            $car_deposit = 0;
            if($type == 2){
                //押金
                if($order['deposit_type'] == 2){
                    //走第三方免押接口判断

                }else{
                    $car_deposit = $merchant_car['car_deposit']??0;
                }
            }
            $coupon_money = 0;
            if($order['coupon_id']){
                $coupon_money = $order['coupon_money'];
                if($coupon_money < $rental_money){
                    $this->error('租赁金额未达到之前的优惠金额');
                }
            }
            $all_money = bcadd(($rental_money-$coupon_money), ($car_deposit+$pick_fee+$return_fee+$order['night_pick_fee']+$order['night_return_fee']+$handle_fee+$order['insurance_money']), 2);
            //查询最后一个换车订单
            $last_order = \app\admin\model\OrderChange::where(['is_delete' => 1, 'user_id' => $order['user_id'], 'order_id' => $order['id']])->where('pay_status', 'in', '2')->order('createtime', 'desc')->find();
            if(!$last_order){
                $diff_money = $type == 1 ? 0 : bcsub($all_money, $order['all_money'], 2);
            }else{
                $diff_money = $type == 1 ? 0 : bcsub($all_money, $last_order['all_money'], 2);
            }
            $data = [
                'car_image' => $merchant_car['car_image'],
                'car_name' => $merchant_car['car_name'],
                'car_number' => $merchant_car['car_number'],
                'car_price' => $merchant_car['car_price'],
                'diff_money' => $diff_money,
            ];
            $this->success('请求成功', '', $data);
        }
    }

}
